package com.morehair.service.wx.impl;

import com.morehair.bean.bo.wx.WxAddGoodsToCartBo;
import com.morehair.bean.bo.wx.WxCheckedCartBo;
import com.morehair.bean.bo.wx.WxDeleteCartGoodsBo;
import com.morehair.bean.bo.wx.WxUpdateCartOfGoodsBo;
import com.morehair.bean.pojo.*;
import com.morehair.bean.vo.wx.WxCartIndexVo;
import com.morehair.bean.vo.wx.WxCheckoutVo;
import com.morehair.config.MallConfig;
import com.morehair.mapper.*;
import com.morehair.service.wx.WxCartService;
import com.morehair.utils.GetNowUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Description:
 * @Author raohui
 * @Date 2021/6/8 13:35
 */
@Service
@Transactional
public class WxCartServiceImlp implements WxCartService {

    @Autowired
    CartMapper cartMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    ProductOfGoodsMapper productOfGoodsMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    CouponUserMapper couponUserMapper;
    @Autowired
    MallSystemMapper mallSystemMapper;
    @Autowired
    MallConfig mallConfig;
    @Autowired
    OrderMapper orderMapper;

    /**
     * 个人购物车里商品展示（index）
     * @return
     */
    @Override
    public WxCartIndexVo indexCart() {
        //购物车前台信息展示用的频繁，抽象成公共方法getWxCartIndexVo()
        return getWxCartIndexVo();
    }

    //购物车前台信息展示
    private WxCartIndexVo getWxCartIndexVo() {
        //获取当前用户信息
        List<Cart> cartItems = getCurrentUserCartItems();
        //1.个人购物车商品总数量和总金额(cartTotal)
        WxCartIndexVo.CartTotalBean cartTotalBean = new WxCartIndexVo.CartTotalBean();
        Integer cartGoodsCount = getGoodsCount(cartItems);
        Double goodsAmount=getGoodsAmount(cartItems);
        Integer checkedGoodsCount=getCheckedGoodsCount(cartItems);
        Double checkedGoodsAmount=getCheckedGoodsAmount(cartItems);
        cartTotalBean.setGoodsCount(cartGoodsCount);
        cartTotalBean.setGoodsAmount(goodsAmount);
        cartTotalBean.setCheckedGoodsCount(checkedGoodsCount);
        cartTotalBean.setCheckedGoodsAmount(checkedGoodsAmount);

        // 2. cartList
        ArrayList<WxCartIndexVo.CartListBean> cartList = new ArrayList<>();
        for (Cart cartItem : cartItems) {
            WxCartIndexVo.CartListBean cartListBean = new WxCartIndexVo.CartListBean();
           cartListBean.setId(cartItem.getId());
           cartListBean.setUserId(cartItem.getUserId());
           cartListBean.setGoodsId(cartItem.getGoodsId());
           cartListBean.setGoodsSn(cartItem.getGoodsSn());
           cartListBean.setGoodsName(cartItem.getGoodsName());
           cartListBean.setProductId(cartItem.getProductId());
           cartListBean.setPrice(cartItem.getPrice().doubleValue());
           cartListBean.setNumber(cartItem.getNumber());
           cartListBean.setSpecifications(Arrays.asList(cartItem.getSpecifications()));
           cartListBean.setChecked(cartItem.getChecked());
           cartListBean.setPicUrl(cartItem.getPicUrl());
           cartListBean.setAddTime(cartItem.getAddTime());
           cartListBean.setUpdateTime(cartItem.getUpdateTime());
           cartListBean.setDeleted(cartItem.getDeleted());
            cartList.add(cartListBean);
        }

        //3.塞数据
        WxCartIndexVo wxCartIndexVo = new WxCartIndexVo();
        wxCartIndexVo.setCartList(cartList);
        wxCartIndexVo.setCartTotal(cartTotalBean);
        return wxCartIndexVo;
    }

    //获取当前用户的商品信息（未删除的，delete=true）
    private List<Cart> getCurrentUserCartItems() {
        CartExample example = new CartExample();
        CartExample.Criteria criteria = example.createCriteria();
        example.setOrderByClause("update_time desc");
        criteria.andDeletedEqualTo(false).andUserIdEqualTo(GetNowUser.getUser().getId());
        return cartMapper.selectByExample(example);
    }

    //获取购物车商品数量（不区分是否选中状态）
    private Integer getGoodsCount(List<Cart> cartItems) {
        Integer goodscount = 0;
        for (Cart cartItem : cartItems) {
            goodscount += cartItem.getNumber();
        }
        return goodscount;
    }

    //获取购物车中商品总额（不区分是否选中状态）
    private Double getGoodsAmount(List<Cart> cartItems) {
        Double goodsAmount = 0.0;
        for (Cart cartItem : cartItems) {
            goodsAmount += cartItem.getNumber() * cartItem.getPrice().doubleValue();
        }
        return goodsAmount;
    }

    //获取购物车中选中的商品总数
    private Integer getCheckedGoodsCount(List<Cart> cartItems) {
        Integer checkedGoodsCount = 0;
        for (Cart cartItem : cartItems) {
            if (cartItem.getChecked()) {
                checkedGoodsCount += cartItem.getNumber();
            }
        }
        return checkedGoodsCount;
    }

    //获取购物车中选中的商品总额
    private Double getCheckedGoodsAmount(List<Cart> cartItems) {
        Double checkedGoodsAmount = 0.0;
        for (Cart cartItem : cartItems) {
            if (cartItem.getChecked()) {
                checkedGoodsAmount += cartItem.getNumber() * cartItem.getPrice().doubleValue();
            }
        }
        return checkedGoodsAmount;
    }




    /**
     * 获取购物车商品数量（包含选中和没选中的）
     * @return
     */
    @Override
    public int getCartGoodsCount() {
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        //更新时间降序
        //方便在数据库查找实时更新的购物商品记录
        cartExample.setOrderByClause("update_time desc");
        criteria.andDeletedEqualTo(false).andUserIdEqualTo(GetNowUser.getUser().getId());
        //查询用户购物车中的商品信息
        List<Cart> cartItems = cartMapper.selectByExample(cartExample);

        //查询购物车中商品数量，每条商品的number+=
        Integer checkedGoodsCount=0;
        for (Cart cartItem : cartItems) {
            if (cartItem.getChecked()) {
                checkedGoodsCount+=cartItem.getNumber();
            }
        }
        return checkedGoodsCount;
    }


    /**
     * 添加商品到购物车
     * @param wxAddGoodsToCartBo
     * @return
     */
    @Override
    public int addGoodsToCart(WxAddGoodsToCartBo wxAddGoodsToCartBo) {
        //根据productsid从规格表中取出商品id对应的规格信息
        ProductOfGoods productOfGoods = productOfGoodsMapper.selectByPrimaryKey(wxAddGoodsToCartBo.getProductId());
        //根据goodsid从商品表中取出对应的商品信息
        Goods goods = goodsMapper.selectByPrimaryKey(wxAddGoodsToCartBo.getGoodsId());

        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andDeletedEqualTo(false).andProductIdEqualTo(wxAddGoodsToCartBo.getProductId()).andUserIdEqualTo(GetNowUser.getUser().getId());
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        int numberCheck = 0;
        if (!carts.isEmpty()) { // 购物车已经存在此商品，只需修改商品的number
            numberCheck+=carts.get(0).getNumber();
        }
        numberCheck+= wxAddGoodsToCartBo.getNumber();
        //判断商品库存
        if (productOfGoods.getNumber()>numberCheck) {//商品库存>添加商品数量
            //从商品表和规格表取出数据放进购物车中
            Cart cart = new Cart();
            cart.setChecked(true);
            cart.setAddTime(new Date());
            cart.setDeleted(false);
            cart.setGoodsId(goods.getId());
            cart.setGoodsName(goods.getName());
            cart.setGoodsSn(goods.getGoodsSn());
            cart.setId(null);
            cart.setNumber(((short) numberCheck));
            cart.setPicUrl(goods.getPicUrl());
            cart.setPrice(goods.getRetailPrice());
            cart.setProductId(wxAddGoodsToCartBo.getProductId());
            cart.setSpecifications(productOfGoods.getSpecifications());
            cart.setUpdateTime(new Date());
            cart.setUserId(GetNowUser.getUser().getId());
            cartMapper.insertSelective(cart);
            return wxAddGoodsToCartBo.getNumber();
        }else {//库存不足
            return 404;
        }

    }

    /**
     * 更新购物车商品（单条商品记录的数量增减）
     * @param wxUpdateCartOfGoodsBo
     * @return
     */
    @Override
    public int updateCart(WxUpdateCartOfGoodsBo wxUpdateCartOfGoodsBo) {
        Cart cart = cartMapper.selectByPrimaryKey(wxUpdateCartOfGoodsBo.getId());
        ProductOfGoods productOfGoods = productOfGoodsMapper.selectByPrimaryKey(wxUpdateCartOfGoodsBo.getProductId());
        int cartOfGoodsNumber = wxUpdateCartOfGoodsBo.getNumber();
        Integer productOfGoodsNumber = productOfGoods.getNumber();
        if (cartOfGoodsNumber > productOfGoodsNumber) {//库存不足
            return 404;
        }
        cart.setNumber((short) wxUpdateCartOfGoodsBo.getNumber());
        int updateNumber = cartMapper.updateByPrimaryKeySelective(cart);
        return updateNumber;
    }

    /**
     * 删除购物车的商品
     * @param wxDeleteCartGoodsBo
     * @return
     */
    @Override
    public WxCartIndexVo deleteCart(WxDeleteCartGoodsBo wxDeleteCartGoodsBo) {
        Integer[] productIds = wxDeleteCartGoodsBo.getProductIds();
        Cart cart = new Cart();
        cart.setDeleted(true);
        CartExample cartExample1 =new CartExample();
        CartExample.Criteria criteria = cartExample1.createCriteria();
        criteria.andUserIdEqualTo(GetNowUser.getUser().getId()).andDeletedEqualTo(false).andProductIdIn(Arrays.asList(productIds));
        cartMapper.updateByExampleSelective(cart,cartExample1);
        WxCartIndexVo wxCartIndexVo = getWxCartIndexVo();
        return wxCartIndexVo;
    }


    /**
     * 选择或取消选择商品
     * @param wxCheckedCartBo
     * @return
     */
    @Override
    public WxCartIndexVo checkedCart(WxCheckedCartBo wxCheckedCartBo) {
        List<Integer> productIds = wxCheckedCartBo.getProductIds();
        Cart cart = new Cart();
        //选择或取消选择的关键代码，非常精彩的一笔，nice
        cart.setChecked(wxCheckedCartBo.getIsChecked()==1);
        //1.update 修改选中状态
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andDeletedEqualTo(false).andUserIdEqualTo(GetNowUser.getUser().getId()).andProductIdIn(productIds);
        cartMapper.updateByExampleSelective(cart, cartExample);
        //2.index回显购物车列表
        return getWxCartIndexVo();
    }

    /**
     * 下单前信息确认
     * @param cartId
     * @param addressId
     * @param couponId
     * @param grouponRulesId
     * @return
     */
    @Override
    public WxCheckoutVo checkoutOrder(Integer cartId, Integer addressId, Integer couponId, Integer grouponRulesId) {
        WxCheckoutVo wxCheckoutVo = new WxCheckoutVo();
        ArrayList<WxCheckoutVo.CheckedGoodsListBean> checkedGoodsListBeans = new ArrayList<>();

        // 设置地址（默认地址）
        AddressExample addressExample = new AddressExample();
        AddressExample.Criteria criteria = addressExample.createCriteria();
        criteria.andDeletedEqualTo(false).andUserIdEqualTo(GetNowUser.getUser().getId()).andIsDefaultEqualTo(true);

        List<Address> addresses = addressMapper.selectByExample(addressExample);
        for (Address address : addresses) {
            if (address.getIsDefault()) {
                wxCheckoutVo.setAddressId(address.getId());
            }
            WxCheckoutVo.CheckedAddressBean addressBean = new WxCheckoutVo.CheckedAddressBean();
            addressBean.setId(address.getId());
            addressBean.setName(address.getName());
            addressBean.setUserId(address.getUserId());
            addressBean.setProvinceId(address.getProvinceId());
            addressBean.setCityId(address.getCityId());
            addressBean.setAreaId(address.getAreaId());
            addressBean.setAddress(address.getAddress());
            addressBean.setMobile(address.getMobile());
            addressBean.setDefault(address.getIsDefault());
            addressBean.setAddTime(address.getAddTime());
            addressBean.setUpdateTime(address.getUpdateTime());
            addressBean.setDeleted(address.getDeleted());
            //塞进去
            wxCheckoutVo.setCheckedAddress(addressBean);
        }

        //获取购买的商品信息, 得到 goodsPrice
        Double goodsTotalPrice = 0.0;
        Double orderTotalPrice = 0.0;
        Double actualPrice = 0.0;
        CartExample cartExample = new CartExample();
       CartExample.Criteria cartExampleCriteria = cartExample.createCriteria();
        if (cartId != 0) {
            // 快速购买
            cartExampleCriteria.andDeletedEqualTo(false).andUserIdEqualTo(GetNowUser.getUser().getId()).andIdEqualTo(cartId);
        } else {
            // 购物车结算
            cartExampleCriteria.andDeletedEqualTo(false).andUserIdEqualTo(GetNowUser.getUser().getId()).andCheckedEqualTo(true);
        }

        //查询结算的商品
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        TreeSet<Integer> cartGoodsIds = new TreeSet<>();
        for (Cart cart : carts) {
            WxCheckoutVo.CheckedGoodsListBean cartBean = new WxCheckoutVo.CheckedGoodsListBean();
            cartBean.setId(cart.getId());
            cartBean.setUserId(GetNowUser.getUser().getId());
            cartBean.setGoodsId(cart.getGoodsId());
            cartBean.setGoodsSn(cart.getGoodsSn());
            cartBean.setGoodsName(cart.getGoodsName());
            cartBean.setProductId(cart.getProductId());
            cartBean.setPrice(cart.getPrice().doubleValue());
            cartBean.setNumber(cart.getNumber());
            cartBean.setSpecifications(cartBean.getSpecifications());
            cartBean.setChecked(cart.getChecked());
            cartBean.setPicUrl(cart.getPicUrl());
            cartBean.setAddTime(cart.getAddTime());
            cartBean.setUpdateTime(cart.getUpdateTime());
            cartBean.setDeleted(cart.getDeleted());

            checkedGoodsListBeans.add(cartBean);
            cartGoodsIds.add(cart.getGoodsId());

            double price = cartBean.getPrice() * cartBean.getNumber();
            goodsTotalPrice += price;
            orderTotalPrice += price;
            actualPrice += price;
        }

        wxCheckoutVo.setCheckedGoodsList(checkedGoodsListBeans);
        //TODO: 购物车跳到结算界面前的商品数量判断，但需要修改前端代码
        int i = -1;
        for (WxCheckoutVo.CheckedGoodsListBean g : checkedGoodsListBeans) {
            int numberInCart = g.getNumber();
            ProductOfGoods productOfGoods = productOfGoodsMapper.selectByPrimaryKey(g.getProductId());
            Integer stock = productOfGoods.getNumber();
            if (stock < numberInCart) {
                WxCheckoutVo r1 = new WxCheckoutVo();
                ArrayList<WxCheckoutVo.CheckedGoodsListBean> r2 = new ArrayList<>();
                r2.add(g);
                r1.setGrouponRulesId(i);
                r1.setCheckedGoodsList(r2);
                return r1;
            }
            i--;
        }

//        // 搞运费, 得到 orderTotalPrice
        Double freightMin = Double.valueOf(mallConfig.getExpressFreightMin());
        Double freightValue = Double.valueOf(mallConfig.getExpressFreightValue());
        // 如果低于免运费的标准, 得到 orderTotalPrice
        if (goodsTotalPrice < freightMin) {
            // 附加上运费
            wxCheckoutVo.setFreightPrice(freightValue);
            orderTotalPrice += freightValue;
            //actualPrice = orderTotalPrice;
        }

        // 搞 availableCouponLength
        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria couponExampleCriteria = couponUserExample.createCriteria();
        couponExampleCriteria.andDeletedEqualTo(false).andUserIdEqualTo(GetNowUser.getUser().getId()).andStatusEqualTo((short) 0)
                .andEndTimeGreaterThan(new Date());
        List<CouponUser> userCoupons =couponUserMapper.selectByExample(couponUserExample);

        Integer availableCouponLength = 0;
        TreeSet<Integer> availableCouponIds = new TreeSet<>();
        for (CouponUser couponUser : userCoupons) {
            // 找该优惠券信息
            Coupon coupon = couponMapper.selectByPrimaryKey(couponUser.getCouponId());
            if (coupon == null || coupon.getDeleted()) {
                // 优惠券被删了
                couponUser.setDeleted(true);
                couponUserMapper.updateByPrimaryKeySelective(couponUser);
                continue;
            }
            if (goodsTotalPrice < coupon.getMin().doubleValue()) {
                // 优惠券不够满减
                continue;
            }
            if (coupon.getGoodsType() == 1) {
                // TODO: 按指定类型
            }
            if (coupon.getGoodsType() == 2) {
                // TODO: 按指定商品
                boolean available = false;

                for (Object goodsId : coupon.getGoodsValue()) {
                    if (cartGoodsIds.contains(goodsId)) {
                        available = true;
                        break;
                    }
                }
                if (!available) {
                    continue;
                }
            }
            availableCouponLength++;
            availableCouponIds.add(couponUser.getId());
        }
        wxCheckoutVo.setAvailableCouponLength(availableCouponLength);


        // 检查当前选中的优惠券, 得到 actualPrice
//        if (availableCouponIds.contains(userCouponId)) {
//            CskaoyanmallCouponUser userCoupon = userCouponMapper.selectByPrimaryKey(userCouponId);
//            if (userCoupon != null && !userCoupon.getDeleted()) {
//
//            }
//        }
        CouponUser userCoupon = couponUserMapper.selectByPrimaryKey(couponId == null ? -1 : couponId);
        if (userCoupon != null && !userCoupon.getDeleted() && availableCouponIds.contains(couponId)) {
            Integer couponId1 = userCoupon.getCouponId();
            Coupon coupon = couponMapper.selectByPrimaryKey(couponId1);
            BigDecimal discount = coupon.getDiscount();
            orderTotalPrice -= discount.doubleValue();
            //actualPrice= orderTotalPrice;
            wxCheckoutVo.setCouponId(couponId);
            wxCheckoutVo.setCouponPrice(discount.doubleValue());
        } else {
            // couponId = -1 时 available 才生效
            // 所以没有选择优惠券时(形参传来couponId=0) 一个设-1 一个设0
            wxCheckoutVo.setCouponId(-1);
            wxCheckoutVo.setCouponPrice(0.0);
        }


        // 最后灌其他数据
        wxCheckoutVo.setGrouponRulesId(0);
        wxCheckoutVo.setGrouponPrice(2.0);
        wxCheckoutVo.setGoodsTotalPrice(goodsTotalPrice);
        wxCheckoutVo.setOrderTotalPrice(orderTotalPrice);     // order_price = goods_price + freight_price - coupon_price
        wxCheckoutVo.setActualPrice(orderTotalPrice);         // actual_price = order_price - integral_price

        return wxCheckoutVo;
    }



    @Override
    public Integer fastaddGoods(WxAddGoodsToCartBo wxAddGoodsToCartBo) {

        if (GetNowUser.getUser().getId()==null) {
            return -1;
        }
        ProductOfGoods productOfGoods = productOfGoodsMapper.selectByPrimaryKey(wxAddGoodsToCartBo.getProductId());
        Goods goods = goodsMapper.selectByPrimaryKey(wxAddGoodsToCartBo.getGoodsId());
        Address address = addressMapper.selectByPrimaryKey(GetNowUser.getUser().getId());

        // 立即购买需要判断库存
        CartExample cartExample = new CartExample();
        CartExample.Criteria cartExampleCriteria = cartExample.createCriteria();
        cartExampleCriteria.andUserIdEqualTo(GetNowUser.getUser().getId()).andDeletedEqualTo(false).andProductIdEqualTo(wxAddGoodsToCartBo.getProductId());
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        int numberCheck = 0;
        if (!carts.isEmpty()) { // 如果已存在于购物车，给加上
            numberCheck += carts.get(0).getNumber();
        }
        numberCheck += wxAddGoodsToCartBo.getNumber();
        Integer stock = productOfGoods.getNumber();
        if (stock < numberCheck) {
            return -200;
        }

//        Cart cart = new Cart();
//        // 快速下单的逻辑
//        cart.setUserId(GetNowUser.getUser().getId());
//        cart.setGoodsId(wxAddGoodsToCartBo.getGoodsId());
//        cart.setGoodsSn(goods.getGoodsSn());
//        cart.setGoodsName(goods.getName());
//        cart.setProductId(wxAddGoodsToCartBo.getProductId());
//        cart.setPrice(productOfGoods.getPrice());
//        cart.setNumber((short) wxAddGoodsToCartBo.getNumber());
//        cart.setSpecifications(productOfGoods.getSpecifications());
//        cart.setChecked(true);
//        cart.setPicUrl(goods.getPicUrl());
//        cart.setUpdateTime(new Date());
//        cart.setAddTime(new Date());
//        int insert = cartMapper.insertSelective(cart);

        Order order = new Order();
        order.setUserId(GetNowUser.getUser().getId());
        order.setOrderSn(goods.getGoodsSn());
        order.setOrderStatus((short) 101);
     //   order.setConsignee(address.getName());
        order.setMobile("18270929385");
        order.setIntegralPrice(BigDecimal.valueOf(0.0));
        order.setAddress("武汉市");
        order.setGoodsPrice(goods.getRetailPrice());
        order.setConsignee("饶慧");
        order.setFreightPrice(BigDecimal.valueOf(8));
        order.setCouponPrice(BigDecimal.valueOf(10));
        order.setGrouponPrice(BigDecimal.valueOf(0.0));
        order.setComments((short) 0);
        BigDecimal price = BigDecimal.valueOf(goods.getRetailPrice().intValue() + 8 + 10);
        order.setActualPrice(price);
        order.setOrderPrice(price);
        order.setDeleted(false);
        order.setUpdateTime(new Date());
        order.setAddTime(new Date());
        orderMapper.insertSelective(order);
        //查刚刚插入
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andUserIdEqualTo(GetNowUser.getUser().getId()).andDeletedEqualTo(false);
        List<Order> orders = orderMapper.selectByExample(orderExample);
        return orders.get(0).getId();
    }
}
